using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using System.IO;
using FileDownloadServer;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Win32.Dialogs;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UITesting;
using Tests.Properties;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using System.Linq;
using FluentAssertions;
using ArtOfTest.Common.Win32;
using System.Diagnostics;

namespace Tests
{
	class FileDownloadServerClient
	{
		private readonly Uri webApplicationAddress;

		public FileDownloadServerClient(Uri webApplicationAddress)
		{
			this.webApplicationAddress = webApplicationAddress;
		}

		public async Task<Uri> ConfigureDownload(string fileName, FileDownloadProperties properties)
		{
			using (var client = new HttpClient())
			{
				client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
				var downloadAddress = MakeUri(fileName);
				var response = await client.PutAsJsonAsync(downloadAddress.AbsoluteUri, properties);
				await Validate(response);

				return downloadAddress;
			}
		}

		private Uri MakeUri(string downloadFileName)
		{
			return new Uri(ControllerAddress, downloadFileName);
		}

		private Uri ControllerAddress
		{
			get
			{
				return new Uri(webApplicationAddress, "api/server/");
			}
		}

		private static async Task Validate(HttpResponseMessage response)
		{
			if (!response.IsSuccessStatusCode)
			{
				var error = await response.Content.ReadAsAsync<HttpError>();
				var formattedError = String.Join(Environment.NewLine, error.Keys.Select(key => String.Format("{0}: {1}", key, error[key])));
				throw new Exception("Couldn't configure download; the server produced an error:\n" + formattedError);
			}

			response.EnsureSuccessStatusCode();
		}
	}
}
